﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web;

namespace iwss.Document.Layouts.iwss.Document.Action
{
    public partial class Share : LayoutsPageBase
    {
        public SPList ShareLib { get { return SPContext.Current.Web.Lists.TryGetList("共享库"); } }
        public SPList DocLib { get { return SPContext.Current.Web.Lists.TryGetList("文档库"); } }

        public List<string> docs
        {
            get
            {
                if (Request["docs"].IsNullOrEmpty()) return new List<string>();
                return HttpUtility.HtmlDecode(Request["docs"]).Split(',').ToList();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            btAdd.Click += new EventHandler(btAdd_Click);
            btDelete.Click += new EventHandler(btDelete_Click);
            btSure.Click += new EventHandler(btSure_Click);
            //if (!IsPostBack)
            //    init();
        }

        List<SPUser> ShareUsers = new List<SPUser>();
        void btSure_Click(object sender, EventArgs e)
        {
            try
            {
                selectedUsers.ResolvedEntities.ToArray().ToList().ForEach(p =>
                {

                    PickerEntity pickitem = p as PickerEntity;

                    switch (pickitem.EntityType)
                    {
                        case "SecGroup":
                            AppendUser(SPContext.Current.Web.AllUsers.Cast<SPUser>().ToList());
                            break;
                        case "User":
                            AppendUser(SPContext.Current.Web.SiteUsers[pickitem.Key]);
                            break;
                        default:
                            int spGroupID = int.Parse(pickitem.EntityData["SPGroupID"].EToString());
                            SPGroup selectGroup = SPContext.Current.Web.SiteGroups.GetByID(spGroupID);
                            AppendUser(selectGroup.Users.Cast<SPUser>().ToList());
                            break;
                    }
                });

                if (docs.Count == 0 || ShareUsers.Count == 0)
                {
                    Page.Alert("请选择要共享的人");
                    return;
                }

                List<SPFile> Docs = new List<SPFile>();
                int id = -1;
                docs.ForEach(p =>
                {
                    if (int.TryParse(p, out id))
                    {
                        Docs.Add(DocLib.GetItemById(id).File);
                    }
                });

                Docs.ForEach(p =>
                {
                    AddNewShareItem(ShareUsers, p);
                });
                Page.OKAndCloseDlg("共享成功");
            }
            catch (Exception ex)
            {
                Page.Alert("被共享的用户未初始化，待用户首次登陆后再共享即可。");
            }

        }

        private void AppendUser(SPUser user)
        {
            if (ShareUsers.FirstOrDefault(p => p.ID == user.ID) == null)
                ShareUsers.Add(user);
        }

        private void AppendUser(List<SPUser> users)
        {
            users.ForEach(p => AppendUser(p));
        }


        private void AddNewShareItem(List<SPUser> shareUsers, SPFile Doc)
        {
            shareUsers.ForEach(p =>
            {
                var newShareItem = ShareLib.AddItem();
                newShareItem["iwss_Sharer"] = p;
                newShareItem["iwss_Url"] = Doc.ServerRelativeUrl;
                newShareItem["Title"] = Doc.Name;
                newShareItem["iwss_LinkID"] = Doc.Item.ID;
                newShareItem.Web.AllowUnsafeUpdates = true;
                newShareItem.Update();
                newShareItem.Web.AllowUnsafeUpdates = false;
            });
        }



        void btDelete_Click(object sender, EventArgs e)
        {

            tvSet.CheckedNodes.All().ToList().ForEach(p =>
            {
                tvFrom.Nodes.Add(new TreeNode(p.Text, p.Value));
            });


            tvSet.CheckedNodes.All().ToList().ForEach(p =>
            {
                tvSet.Nodes.Remove(p);
            });
        }

        void btAdd_Click(object sender, EventArgs e)
        {
            tvFrom.CheckedNodes.All().ToList().ForEach(p =>
            {

                tvSet.Nodes.Add(new TreeNode(p.Text, p.Value));
            });



            tvFrom.Nodes.All().ToList().ForEach(p =>
            {
                if (tvFrom.CheckedNodes.All().Contains(p))
                    tvFrom.Nodes.Remove(p);
            });

        }


        public void init()
        {
            SPUserCollection users = SPContext.Current.Web.SiteUsers;
            foreach (SPUser user in users)
            {
                //if (ExistUser != null && !ExistUser(user.Name))
                //{
                tvFrom.Nodes.Add(new TreeNode(user.Name, user.LoginName));
                //}
            }
        }
    }
}
